from rest_framework import serializers
from zmad.models import ZTPResource
from .models import UserActivityLog, StrategyLog


# mogno log_time字段存入为东八区时间.即东八区时间当做utc来处理.
class NoTimezoneDatetimefield(serializers.DateTimeField):

    def default_timezone(self):
        return None


class MongoBaseSerializer(serializers.Serializer):
    log_time = NoTimezoneDatetimefield(format='%Y-%m-%d %H:%M:%S')
    id = serializers.CharField(read_only=True)


class UserActivityLogSerializer(serializers.ModelSerializer, MongoBaseSerializer):
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        try:
            city = representation.get('city')
            if not city:
                representation['city'] = '本地'

            resource = representation.get('resource')
            if resource:
                ztp_resource = ZTPResource.objects.get(id=resource)
                representation['resource'] = ztp_resource.name  # 替换resource字段的值为ZTPResource的name
            else:
                representation['resource'] = None
        except ZTPResource.DoesNotExist:
            representation['resource'] = None  # 或者设置一个默认值
        if representation['resource']:
            representation['activity'] = '访问应用 %s' % representation['resource']
        return representation

    class Meta:
        model = UserActivityLog
        fields = '__all__'


class UserWarningSerializer(serializers.ModelSerializer, MongoBaseSerializer):

    class Meta:
        model = StrategyLog
        fields = ["username", "platform", "uid", "log_time"]